﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BinaryStudentStorage
{
    class BinStorage
    {
        static void AddStudent(Student std)
        {
            FileStream fs = new FileStream("data.bin", FileMode.Append, FileAccess.Write);
            using (BinaryWriter outFile = new BinaryWriter(fs))
            {
                outFile.Write(std.FirstName);
                outFile.Write(std.LastName);
                outFile.Write(std.FacultyNumber);
            }
        }

        static void PrintAllStudents()
        {
            FileStream fs = new FileStream("data.bin", FileMode.Open, FileAccess.ReadWrite);
            using (BinaryReader outFile = new BinaryReader(fs))
            {
                while (outFile.BaseStream.Position < outFile.BaseStream.Length)
                {
                    string firstName = outFile.ReadString();
                    string lastName = outFile.ReadString();
                    int facNum = outFile.ReadInt32();
                    Student std = new Student(firstName, lastName, facNum);
                    Console.WriteLine(std);
                }
            }
        }

        static void DeleteStudent(int facNumToDel)
        {
            FileStream freader = new FileStream("data.bin", FileMode.Open, FileAccess.ReadWrite);
            FileStream fwriter = new FileStream("data2.bin", FileMode.Create, FileAccess.Write);

            using (BinaryReader inFile = new BinaryReader(freader))
            {
                using (BinaryWriter outFile = new BinaryWriter(fwriter))
                {
                    while (inFile.BaseStream.Position < inFile.BaseStream.Length)
                    {
                        string firstName = inFile.ReadString();
                        string lastName = inFile.ReadString();
                        int facNum = inFile.ReadInt32();
                        if (facNum == facNumToDel)
                        {
                            continue;
                        }
                        outFile.Write(firstName);
                        outFile.Write(lastName);
                        outFile.Write(facNum);
                    }
                }
            }
            File.Delete("data.bin");
            File.Move("data2.bin", "data.bin");
        }

        static void Main()
        {
            Student std1 = new Student("Ivan", "Pertov", 121207101);
            Student std2 = new Student("Petar", "Ivanov", 121207111);
            Student std3 = new Student("Petko", "Ivanov", 121207121);

            AddStudent(std1);
            AddStudent(std2);
            AddStudent(std3);
            PrintAllStudents();
            DeleteStudent(121207111);
            Console.WriteLine("---------------------------------");
            PrintAllStudents();
        }
    }
}
